<template>
  <div>
    <el-tabs v-model="activeName" type="card" @tab-change="handleClick">
      <template v-for="item in tabsList" :key="item.name">
        <el-tab-pane :label="item.label" :name="item.name"></el-tab-pane>
      </template>
    </el-tabs>

    <div class="tabs_content">
      <div class="tabs_operations">
        <div>
          <el-input
            v-model="searchVal"
            clearable
            style="width: 200px"
            @keyup.enter="getTableData()"
            @clear="getTableData()"
          >
            <template #append>
              <el-button type="primary" @click="getTableData()">搜索</el-button>
            </template>
          </el-input>
        </div>
        <div>
          <el-button type="primary" @click="handleAdd">新增</el-button>
          <el-button type="danger" @click="deleteSelectRow">删除</el-button>
        </div>
      </div>
      <vxe-table
        ref="xTable"
        v-loading="tLoading"
        :data="tableData"
        border
        highlight-hover-row
        highlight-current-row
        auto-resize
        row-id="id"
        @checkbox-change="handleCheckboxChange"
        @checkbox-all="handleCheckboxChange"
        @cell-click="handleRowClick"
      >
        <vxe-column type="checkbox" width="60"></vxe-column>
        <vxe-column
          v-for="column in columnData"
          :key="column.columnName"
          :field="column.columnName"
          :title="column.columnLabel"
        ></vxe-column>
      </vxe-table>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'

import {
  getAllQuestionList,
  deleteQuestionByIds,
  updateQuestionById,
  getAllAccountList,
  deleteAccountByIds,
  updateAccountById,
  queryAllElementList,
  getElementById,
  updateElementById,
  deleteElementByIds,
  queryAllIngredientList,
  getIngredientById,
  updateIngredientById,
  deleteIngredientByIds,
  queryAllFoodList,
  deleteFoodByIds
} from './api.js'

import { useRouter } from 'vue-router'
const router = useRouter()

import { ElMessage } from 'element-plus'

const activeName = ref('questionManager')
const tabsList = reactive([
  {
    label: '题库',
    name: 'questionManager',
  },
  {
    label: '用户',
    name: 'userManager',
  },
  {
    label: '食谱',
    name: 'recipeManager',
  },
  {
    label: '食材',
    name: 'foodManager',
  },
  {
    label: '元素',
    name: 'nutrientElementManager',
  }
])
const xTable = ref(null)
const tableData = ref([])
const columnData = ref([
  { columnName: 'content', columnLabel: '名称' },
  { columnName: 'icon', columnLabel: '图标' },
])
const tLoading = ref(false)
const selectRow = ref([])
const searchVal = ref('')

// 动态获取
const queryApi = computed(() => {
  const map = {
    'questionManager': getAllQuestionList,
    'userManager': getAllAccountList,
    'nutrientElementManager': queryAllElementList,
    'foodManager': queryAllIngredientList,
    'recipeManager': queryAllFoodList
  }
  return map[activeName.value]
})
const deleteApi = computed(() => {
  const map = {
    'questionManager': deleteQuestionByIds,
    'userManager': deleteAccountByIds,
    'nutrientElementManager': deleteElementByIds,
    'foodManager': deleteIngredientByIds,
    'recipeManager': deleteFoodByIds
  }
  return map[activeName.value]
})
const searchKey = computed(() => {
  const map = {
    'questionManager': 'content',
    'userManager': 'user_name',
    'nutrientElementManager': 'name',
    'foodManager': 'name',
    'recipeManager': 'name'
  }
  return map[activeName.value] || 'name'
})
const infoURL = computed(() => {
  const infoMap = {
    'questionManager': '/settings/questionManager',
    'userManager': '/settings/userManager',
    'nutrientElementManager': '/settings/nutrientManager',
    'foodManager': '/settings/ingredientsManager',
    'recipeManager': '/settings/foodManager'
  }
  return infoMap[activeName.value]
})

onMounted(() => {
  // 获取缓存页签
  const oldActiveName = JSON.parse(localStorage.getItem('activeName'))
  if (oldActiveName) {
    activeName.value = oldActiveName
  }

  if (activeName.value === 'recipeManager') {
    // 食谱的列头
    columnData.value = [
      { columnName: 'name', columnLabel: '名称' },
      { columnName: 'alias', columnLabel: '别名' },
      { columnName: 'tag', columnLabel: '标签' },
      // { columnName: 'icon', columnLabel: '图标' },
    ]
  } else if (activeName.value === 'userManager') {
    columnData.value = [
      { columnName: 'user_name', columnLabel: '账号' },
      { columnName: 'account', columnLabel: '用户名' },
    ]
  }

  // getTableData()
})

const getTableData = () => {
  // 查询表格数据
  tLoading.value = true
  queryApi.value().then(res => {
    const result = res.result
    if (searchVal.value) {
      tableData.value = result.filter(item => item[searchKey.value].includes(searchVal.value))
    } else {
      tableData.value = result
    }
    tLoading.value = false
  })
}

const handleClick = () => {
  columnData.value[0].columnName = searchKey.value
  // 缓存在本地
  localStorage.setItem('activeName', JSON.stringify(activeName.value))
  getTableData()
}

const handleRowClick = ({ row }) => {
  // 修改
  router.push({ path: infoURL.value, query: { id: row.id } })
}

const handleAdd = () => {
  router.push({ path: infoURL.value })
}

const deleteSelectRow = () => {
  const ids = selectRow.value.map(item => item.id)
  deleteApi.value({ids}).then(res => {
    getTableData()
    selectRow.value = []
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
  })
}

const handleCheckboxChange = ({ records }) => {
  selectRow.value = records
}
</script>

<style lang="scss" scoped>
.tabs_content {
  padding: 20px;
  .tabs_operations {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    .el-button {
      border-radius: 50px;
    }
  }
  ::v-deep .vxe-table--body-wrapper {
    height: calc(100vh - 250px);
  }
}
</style>
